﻿using System;
using UnityEngine;
using UnityEngine.UI;

public class ApplicationItem : MonoBehaviour
{
    Apply m_Data;
    public Apply data => m_Data;

    public NetworkImage icon;
    public Text nameText;
    public Text applyStatusText;
    public Text applyTimeText;

    Texture2D m_Texture;
    float iconSize;
    void Awake()
    {
        iconSize = icon.GetComponent<RectTransform>().rect.width;
        if(m_Data == null)
            icon.Init("");
    }

    public void Init(Apply apply, Action<ApplicationItem> onSelectApplicationItem)
    {
        m_Data = apply;

        if(iconSize <= 0)
            iconSize = icon.GetComponent<RectTransform>().rect.width;

        long opponentUserId = m_Data.sourceUserId == MGame.instance.MUser.id ? m_Data.targetUserId : m_Data.sourceUserId;

        RequestServerController.instance.RequestUserInfo(opponentUserId, (userInfo) =>
        {
            if(nameText)
                nameText.text = userInfo.name;
            if (applyStatusText)
            {
                if (apply.sourceUserId == MGame.instance.MUser.id)
                {
                    if (apply.result == Apply.ApplyResult_Fail)
                        applyStatusText.text = "对方已拒绝申请";
                    else if (apply.result == Apply.ApplyResult_Suc)
                        applyStatusText.text = "对方已同意申请";
                    else if (apply.result == Apply.Applying)
                        applyStatusText.text = "等待对方查看";
                }
                else
                {
                    if (apply.result == Apply.ApplyResult_Fail)
                        applyStatusText.text = "已拒绝";
                    else if (apply.result == Apply.ApplyResult_Suc)
                        applyStatusText.text = "已同意";
                    else if (apply.result == Apply.Applying)
                        applyStatusText.text = "等待查看";
                }
            }
            if(applyTimeText)
                applyTimeText.text = ApplyUserPanel.GetDateTimeStrWithTimestamp(apply.applyTime);

            this.icon.Init(userInfo.icon);

            //if (m_Texture != null)
            //    DestroyImmediate(m_Texture);
            //m_Texture = UnityFunctions.GetTextureWithByte(userInfo.icon);
            //UnityFunctions.SetRawImage(this.icon, m_Texture, iconSize,true);
        });
    }

    public void OnClickView()
    {
        ApplyUserPanel view = this.GetComponentInParent<UIController>().ShowUI<ApplyUserPanel>();
        view.Init(m_Data);
    }

    void OnDestroy()
    {
        //if (this.icon.texture)
        //    Destroy(icon.texture);
    }
}